package com.totoro.controller.request;

import com.totoro.controller.RegisterFormController;
import com.totoro.pojo.*;
import com.totoro.service.*;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author TOTORO
 * @date 2021/6/28 9:13
 */
@Controller
@RequestMapping("/user")
public class UserRequestController {
    static Logger logger = Logger.getLogger(UserRequestController.class);

    @Autowired
    AddressService addressService;
    @Autowired
    UserService userService;
    @Autowired
    OrderService orderService;
    @Autowired
    EvaluationService evaluationService;
    @Autowired
    SellerService sellerService;
    @Autowired
    ReturnService returnService;
    @Autowired
    ProductService productService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    ShopService shopService;

    @GetMapping("/quitLogin")
    public String quitLoginStatus(HttpSession session){
        session.invalidate();
        return "redirect:/";
    }

    /**
     * 跳转至个人中心
     * @param session
     * @return
     */
    @RequestMapping("/index")
    public String goUserHome(HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        // 用来计数的订单
        List<MarketOrder> countOrders = orderService.findAllOrder(user.getUserId(), 0, 0);
        // 计算所有不同订单种类数量 ，初始化集合
        Map<String, Integer> countMap = new HashMap<>();
        countOrders.forEach((v)->countMap.put(v.getOrderStatus()+"",(countMap.get(v.getOrderStatus()+"")==null?0:countMap.get(v.getOrderStatus()+"")) +1));
        model.addAttribute("typesCount", countMap);
        model.addAttribute("user", user);

        // 查询推荐商品
        // 推荐思路：首先查询最近一个月的随机几条用户足迹（浏览过的商品）做分割关键字查询，
        // 再按照销量最高的随机几条商品记录
        // 其次是以搜索最高的商品记录
        List<Product> myHistories = new ArrayList<>();
        if(null != user){
            myHistories = productService.findRecentRandHistoryProducts(user.getUserId());
            Collections.reverse(myHistories);
        }
        List<Product> sourceProducts = new ArrayList<>();
        for (Product product : myHistories) {
            sourceProducts.add(product);
        }
        List<Product> products1 = productService.findHotRandHistoryProducts();
        List<Product> products2 = productService.findKeywordAgoProducts();

        sourceProducts.addAll(products1);
        sourceProducts.addAll(products2);
        // 去重
        List<Product> finalProducts = sourceProducts.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(Product::getId))),
                ArrayList::new));
        if(finalProducts.size() > 54){
            finalProducts = finalProducts.subList(0,54);
        }

        // 混淆集合
        Collections.shuffle(finalProducts);
        model.addAttribute("recommendProducts", finalProducts);
        return "/include/user/user_index";
    }

    /**
     * 跳转至购买过的宝贝
     * @param session
     * @return
     */
    @RequestMapping("/boughtBaby")
    public String goBuyBaby(@RequestParam(value = "tabCode", required = false, defaultValue = "") String tabCode,
                            @RequestParam(value = "productTitleOrOrderId", required = false, defaultValue = "") String productTitleOrOrderId,
                            @RequestParam(value = "evaStatus", required = false, defaultValue = "999") int evaStatus,
                            @RequestParam(value = "startTime", required = false, defaultValue = "") String startTime,
                            @RequestParam(value = "endTime", required = false, defaultValue = "") String endTime,
                            @RequestParam(value = "sellerName", required = false, defaultValue = "") String sellerName,
                            @RequestParam(value = "transactionStatus", required = false, defaultValue = "999") int transactionStatus,
                            @RequestParam(value = "nowPage", required = false, defaultValue = "1") int nowPage,
                            HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        // 用来计数的订单
        List<MarketOrder> countOrders = orderService.findAllOrder(user.getUserId(), 0, 0);
        // 真正的订单
        List<MarketOrder> marketOrderList = null;
            int status = tabCode.equals("waitPay")?1:tabCode.equals("waitSend")?2:tabCode.equals("waitConfirm")?3:tabCode.equals("waitRate")?4:0;
            // 买家查询多条件pojo
            BuyerOrderFind buyerOrderFind = new BuyerOrderFind(user.getUserId(), 0, evaStatus, startTime, endTime, sellerName, transactionStatus, status, productTitleOrOrderId.trim(), nowPage);
            marketOrderList =  orderService.superFindUserOrderId(buyerOrderFind);
        // 计算所有不同订单种类数量 ，初始化集合
        Map<String, Integer> countMap = new HashMap<>();
        countOrders.forEach((v)->countMap.put(v.getOrderStatus()+"",(countMap.get(v.getOrderStatus()+"")==null?0:countMap.get(v.getOrderStatus()+"")) +1));
        model.addAttribute("marketOrders", marketOrderList);
        model.addAttribute("typesCount", countMap);
        model.addAttribute("tabCode", tabCode);
        // 查询一次未分页的
        buyerOrderFind.setNowPage(0);
        int notPaginationLength = orderService.superFindUserOrderId(buyerOrderFind).size();
        model.addAttribute("allPage", notPaginationLength);
        // 根据详情订单号获取所有退货款订单号，map键值对
        Map<String, PrimaryReturn> map = new HashMap<>();
        for (MarketOrder marketOrder : marketOrderList) {
            for (MarketSrOrder marketSrOrder : marketOrder.getMarketSrOrderList()) {
                PrimaryReturn primaryReturn = returnService.findPrimaryReturnByMarketSrId(marketSrOrder.getId());
                if(primaryReturn!=null){
                    map.put(marketSrOrder.getId()+"", primaryReturn);
                }
            }
        }
        model.addAttribute("primaryReturnMap", map);
        return "/include/user/bought_baby";
    }


    /**
     * 跳转至订单回收站
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/list_recyled_items")
    public String goRecyledItems(@RequestParam(value = "curr", defaultValue = "1", required = false) int curr, HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        List<MarketOrder> marketOrderList = orderService.findRecoverOrder(user.getUserId(), curr);
        // 未分页的长度
        int allPage = orderService.notPaginationRecoverOrder(user.getUserId(), 0).length;
        model.addAttribute("marketOrderList", marketOrderList);
        model.addAttribute("allPage", allPage);
        return "include/user/list_recyled_items";
    }

    /**
     * 跳转至购买过的店铺
     * @param session
     * @return
     */
    @RequestMapping("/boughtShop")
    public String goBuyShop(HttpSession session,
                            @RequestParam(value = "curr", required = false, defaultValue = "1") int curr,
                            @RequestParam(value = "categoryId", required = false, defaultValue = "0") int categoryId,
                            @RequestParam(value = "keyword", required = false, defaultValue = "") String keyword,
                            Model model){
        User user = (User) session.getAttribute("user");
        List<BuyShop> shops = productService.findAllUserBuyShopList(user.getUserId(), 0, null, 0);
        // 统计所有分类占据次数
        Map<Category, Integer> categoryCountMap = new HashMap<>();
        Map<Integer, Integer> map = new HashMap<>();
        for (BuyShop shop : shops) {
            map.put(shop.getProduct().getBelongCategoryId(), (null==map.get(shop.getProduct().getBelongCategoryId())?0:map.get(shop.getProduct().getBelongCategoryId()))+1);
        }
        map.forEach((k,v)->{
            categoryCountMap.put(categoryService.byIdFindCategory(k), v);
        });
        model.addAttribute("categoryMap", categoryCountMap);
        return "/include/user/bought_shop";
    }


    /**
     * 跳转至我的积分页面
     * @param session
     * @return
     */
    @RequestMapping("/myIntegral")
    public String goMyIntegral(HttpSession session){
        User user = (User) session.getAttribute("user");
        if(null == user){
            return "redirect:/login.htm";
        }

        return "/include/user/jifen";
    }


    /**
     * 跳转至我的优惠券页面
     * @param session
     * @return
     */
    @RequestMapping("/gotBonus")
    public String goGotBonus(HttpSession session){
        User user = (User) session.getAttribute("user");
        if(null == user){
            return "redirect:/login.htm";
        }
        return "/include/user/got_bonus";
    }

    /**
     * 跳转至天猫足迹页面
     * @param session
     * @return
     */
    @RequestMapping("/tmFoot")
    public String tmFoot(HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        Map<String,List<MyHistory>> myHistories=userService.findUserHistory(user.getUserId());
        model.addAttribute("myHistories",myHistories);
        return "/include/user/tm_foot";
    }

    /**
     * 跳转至我的评价
     * @param session
     * @return
     */
    @RequestMapping("/myComment")
    public String myComment(@RequestParam(value = "findType", required = false, defaultValue = "3") int findType,
                            @RequestParam(value = "showType", required = false, defaultValue = "9999") int showType,
                            @RequestParam(value = "showContent", required = false, defaultValue = "9999") int showContent,
                            HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        if(null == user){
            return "redirect:/login.htm";
        }
        // 判断用户需要查看那种类型的评论
        int id = 0;
        if(findType == 1 || findType == 4){
            // 用户是否为卖家，如果为卖家，则渲染
            if(user.getIsSeller() == 1){
                id = user.getSeller().getId();
            }
        }
        if(findType == 3 || findType == 2){
            id = user.getUserId();
        }
        List<ProductComment> productComments = evaluationService.findUserMultipleEvaluation(findType, id, showType, showContent);
        // 获得统计分数专用的评论集合，在jsp页面使用el进行处理
        List<ProductComment> statisticsList = evaluationService.findUserMultipleEvaluation(1, user.getSeller().getId(), 9999, 9999);
        model.addAttribute("statisticsList", statisticsList);
        model.addAttribute("productComments", productComments);
        model.addAttribute("user", user);
        return "/include/user/my_comment";
    }

    /**
     * 跳转至我的资料
     * @param session
     * @return
     */
    @RequestMapping("/myData")
    public String myData(HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        if(null == user){
            return "redirect:/login.htm";
        }
        // 拿到最新的user，因为可能做了修改，不可用session中的user
        User newUser = userService.findUserById(user.getUserId());
        model.addAttribute("user", newUser);

        return "/include/user/my_data";
    }


    /**
     * 跳转至收货地址
     * @param session
     * @return
     */
    @RequestMapping("/receiptAddress")
    public String receiptAddress(@RequestParam(value = "addrId", required = false, defaultValue = "0") Integer addrId, HttpSession session, Model model){
        // 如果前端路径带了参数过来，则是需要进行修改
        Address address = null;
        if(addrId != 0){
            address = addressService.findAddressByAid(addrId);
            model.addAttribute("update", true);
        }
        model.addAttribute("address", address);
        User user = (User) session.getAttribute("user");
        if(null == user){
            return "redirect:/login.htm";
        }

        // 获取用户ID，拿到该用户的地址记录
        int uid = user.getUserId();
        List<Address> addressList = addressService.findAddressByUid(uid);
        model.addAttribute("addressList", addressList);
        return "/include/user/receipt_address";
    }

    /**
     * 新收货地址的iframe
     * @param session
     * @return
     */
    @RequestMapping("/receiptAddressIframe")
    public String receiptAddressIframe(@RequestParam(value = "addrId", required = false, defaultValue = "0") Integer addrId, @RequestParam("spm") String spm, HttpSession session, Model model){
        // 如果前端路径带了参数过来，则是需要进行修改
        Address address = null;
        if(addrId != 0){
            address = addressService.findAddressByAid(addrId);
            model.addAttribute("update", true);
        }
        model.addAttribute("address", address);
        User user = (User) session.getAttribute("user");
        if(null == user){
            return "redirect:/login.htm";
        }

        // 获取用户ID，拿到该用户的地址记录
        int uid = user.getUserId();
        List<Address> addressList = addressService.findAddressByUid(uid);
        model.addAttribute("addressList", addressList);
        return "forward:/public_page/modify_address.jsp";
    }


    /**
     * 我的收藏
     * @param session
     * @param model
     * @param tab
     * @param value
     * @return
     */
    @RequestMapping("/baby_collect_list")
    public String myCollection(HttpSession session, Model model,
                               @RequestParam(value = "tab", required = false, defaultValue = "1") int tab,
                               @RequestParam(value = "value", required = false, defaultValue = "") String value){
        User user = (User) session.getAttribute("user");
        List<CollectProduct> collectProducts = productService.findAllUserCollectProduct(user.getUserId(), value);
        // 分出已失效的商品
        List<CollectProduct> failProducts = new ArrayList<>();
        // 分出按店铺分组的商品
        Map<Shop, List<CollectProduct>> map = new HashMap<>();
        collectProducts.forEach(v ->{
            if(v.getProduct().getIsLanunched() == 0 || v.getProduct().getIsDelete() == 1){
                failProducts.add(v);
            }
            map.put(v.getProduct().getShop(), new ArrayList<>());
        });
        collectProducts.forEach(v->{
            map.get(v.getProduct().getShop()).add(v);
        });
        model.addAttribute("sameShopBabys", map);
        model.addAttribute("collectProducts", collectProducts);
        model.addAttribute("failProducts", failProducts);
        return "include/user/my_collection";
    }


    /**
     * 跳转至店铺收藏
     * @param session
     * @return
     */
    @RequestMapping("/shop_collect_list")
    public String shopCollect(@RequestParam(value = "keyword", required = false, defaultValue = "") String keyword, HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        if(null == user){
            return "redirect:/login.htm";
        }
        model.addAttribute("user", user);
        Map<CollectShop, List<Product>> shopProduct = shopService.findCollectShop(user.getUserId(), keyword);
        model.addAttribute("shopProduct",shopProduct);
        return "/include/user/shop_collect_list";
    }

}
